package cn.ycq.im.chat.clients;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.sql.Wrapper;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author yuchaoqun
 * @email chaoqunyu9311@163.com
 * @date 2021.03.07 13:20
 */
@Slf4j
public class ChannelListWraper {

    private Map<ChannelId, Channel> channelMap = new ConcurrentHashMap<>();
    private Map<String,Object> extraAttr = new ConcurrentHashMap<>();
    private AtomicBoolean inited =new AtomicBoolean(false);

    public ChannelListWraper addChannel(Channel channel){
        channelMap.put(channel.id(),channel);
        return this;
    }
    public ChannelListWraper removeChannel(ChannelId channelId){
        channelMap.remove(channelId);
        return this;
    }
    public ChannelListWraper setExtAttr(String attrName,Object attrValue){
        this.extraAttr.put(attrName,attrValue);
        return this;
    }
    public boolean hasChannel(ChannelId channelId){
        return channelMap.containsKey(channelId);
    }

    public int channelNum() {
        return channelMap.size();
    }

    public void writeAndFlush(TextWebSocketFrame content){
        String text = content.text();

        for (Map.Entry<ChannelId, Channel> channelEntry : channelMap.entrySet()) {
            ChannelId channelId = channelEntry.getKey();
            Channel channel = channelEntry.getValue();
            try {
                  WebSocketFrame  webSocketFrame = new TextWebSocketFrame(text);
                channel.writeAndFlush(webSocketFrame);
            }catch (Exception e){
                e.printStackTrace();
                channelMap.remove(channelId);
            }
        }
    }

    public boolean isInit() {
        return this.inited.get();
    }

    public void inited() {
        this.inited.set(true);
    }
}
